package cn.webrx;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * <p>功能描述: </p>
 *
 * @author webrx
 * @version 1.0
 * @date 2020-06-11 16:13
 */
@Component
public class QuickStart {
    private static Logger log = LoggerFactory.getLogger(QuickStart.class);
    @Autowired
    private SecurityManager securityManager;
    @Autowired
    private SimpleService simpleService;

    public void run() {
        Subject su = SecurityUtils.getSubject();
        System.out.println(su.isAuthenticated());//false
        UsernamePasswordToken token = new UsernamePasswordToken("lisi", "123456");
        try{
            su.login(token);
        }catch(IncorrectCredentialsException  ice){
            System.out.println("密码错误");
        }catch(Exception e){
            e.printStackTrace();
        }

        su.logout();

        try{
            su.checkRole("user");
        }catch(Exception e){
            System.out.println("没有user角色");
        }
        System.out.println(su.hasRole("admin"));
        try{
            su.checkPermission("read");
            simpleService.readRestrictedCall();
        }catch(Exception e){
            System.out.println("没有read权限");;
        }
    }


    /**
     * Sets the static instance of SecurityManager. This is NOT needed for web applications.
     */
    @PostConstruct
    private void initStaticSecurityManager() {
        SecurityUtils.setSecurityManager(securityManager);
    }
}